﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Drawing;


public partial class WorkSpace : System.Web.UI.Page
{
    DataSet ds = null;
    DataSet dst = null;
    rUser ruser;
    public static string filterstatus;
    public static int sort;
    protected void Page_Load(object sender, EventArgs e)
    {

        if (Session["userid"] == null)
        {

            Response.Redirect("../Default.aspx");
        }
        else
        {

           
            ds = null;
            dst= null;
            ruser = (rUser)Session["userid"];
            try
            {
                string oldfilter = filterstatus;
                string id = Request.QueryString["get"];
                if (id.Equals("pending")) { filterstatus = "pending"; }
                if (id.Equals("assigned")) { filterstatus = "assigned"; }
                if (id.Equals("completed")) { filterstatus = "completed"; }
                if (id.Equals("cancelled")) { filterstatus = "cancelled"; }
                if (id.Equals("paid")) { filterstatus = "paid"; }
                if (id.Equals("all")) { filterstatus = "all"; }

                long strpermiso = (long.Parse(ruser.getPermiso()) & 8);
                if ((strpermiso) != 8 && filterstatus.Equals("paid")) { filterstatus = oldfilter; }
            }
            catch (Exception ex) { filterstatus = "default"; }

            if (!Page.IsPostBack)
            {
                DateTime now = DateTime.Now;
                sort = 0;
                hoy.Text = String.Format("{0:dddd, MMMM d, yyyy}", now).ToUpper();

                name.Text = ruser.getNombre().ToUpperInvariant() + " " + ruser.getApellido().ToUpperInvariant();
                string permiso = ruser.getPermiso();
                string perfil=  ruser.getPerfilId();
                logo.ImageUrl = ruser.getLogo();
                ds= DB.GetOrders(permiso, filterstatus);
                dst = DB.getStatus(perfil);
                if (ds != null)
                {



                    gv_detail.DataSource = ds.Tables["Tabla"];
                    gv_detail.DataBind();
                    Session["OrderList"] = ds;
                    gv_status.DataSource = dst.Tables["Tabla"];
                    gv_status.DataBind();

                }
            }
           
        }
    }
    protected void gv_detail_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Edit") {
            int index = Convert.ToInt32(e.CommandArgument);
            int id = int.Parse(gv_detail.Rows[index].Cells[2].Text);
            Response.Redirect("ODetils.aspx?id=" + id);
        }
    }
    protected void gv_detail_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {    
        if (Session["OrderList"]!=null)
            ds = (DataSet)Session["OrderList"];
   
        if (ds != null)
        {
            gv_detail.PageIndex = e.NewPageIndex;
            gv_detail.DataSource = ds.Tables["Tabla"];
            gv_detail.DataBind();
        }

    }
    protected void lb_rows_limit_SelectedIndexChanged(object sender, EventArgs e)
    {
        int cantidad=int.Parse(lb_rows_limit.SelectedValue);
        gv_detail.PageSize = cantidad;
        if (Session["OrderList"] != null)
            ds = (DataSet)Session["OrderList"];

        if (ds != null)
        {         
            gv_detail.DataSource = ds.Tables["Tabla"];
            gv_detail.DataBind();
        }
    }
    protected void gv_detail_RowDataBound(object sender, GridViewRowEventArgs e)
    {
         ruser = (rUser)Session["userid"];

        
        
      
        if (e.Row.RowType == DataControlRowType.DataRow || e.Row.RowType == DataControlRowType.Header) {

            e.Row.Cells[0].Style.Add("display", "none");     //  hide editbutton
            e.Row.Cells[2].Style.Add("display", "none");    //hide orden id
            e.Row.Cells[3].Style.Add("display", "none");
            e.Row.Cells[22].Style.Add("display", "none");
           // e.Row.Cells[19].Style.Add("display", "none");
           
 

        }
        if (e.Row.RowType == DataControlRowType.Header) {
          
           
            e.Row.Cells[1].Text = "Order id";
            e.Row.Cells[1].Style.Add("style", "text-decoration:none; ");
            
            e.Row.Cells[2].Text = "Order id";
            e.Row.Cells[2].HorizontalAlign = HorizontalAlign.Left;
            e.Row.Cells[3].Text = "Order #";
            e.Row.Cells[3].Style.Add("style", "text-decoration:none; ");
            e.Row.Cells[4].Text = "Due Date";
            e.Row.Cells[4].Style.Add("style", "text-decoration:none; ");
            
            e.Row.Cells[5].Text = "Due Time";
            e.Row.Cells[5].Style.Add("style", "text-decoration:none; ");
            
            e.Row.Cells[10].Text = "Street No.";
            e.Row.Cells[10].Style.Add("style", "text-decoration:none; ");
           e.Row.Cells[11].Text = "Street Address";
            e.Row.Cells[11].Style.Add("style", "text-decoration:none; ");
           
            e.Row.Cells[14].Text = "Zip";
            e.Row.Cells[14].Style.Add("style", "text-decoration:none; ");
            e.Row.Cells[16].Text = "Proc";
            e.Row.Cells[16].Style.Add("style", "text-decoration:none; ");
            e.Row.Cells[17].Text = "Drv";
            e.Row.Cells[17].Style.Add("style", "text-decoration:none; ");
            e.Row.Cells[18].Text = "PI Comments";
            e.Row.Cells[18].Style.Add("style", "text-decoration:none; ");
            e.Row.Cells[20].Text = "Appt Date";
            e.Row.Cells[20].Style.Add("style", "text-decoration:none; ");
            e.Row.Cells[21].Text = "Appt Comments";
            e.Row.Cells[21].Style.Add("style", "text-decoration:none; ");
            for (int k = 0; k < 22; k++ )
            {
                e.Row.Cells[k].HorizontalAlign = HorizontalAlign.Left;
            }
            e.Row.HorizontalAlign = HorizontalAlign.Left;
        }

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.HorizontalAlign = HorizontalAlign.Left;
            if (e.Row.Cells[22].Text == "YES")
            {
               // e.Row.ForeColor = System.Drawing.Color.Red;
                e.Row.Font.Bold = true;
            }
           /* e.Row.Cells[1].Width = 100;//orden# con link

            e.Row.Cells[4].Width = 90;//duedate
            e.Row.Cells[5].Width = 100;//duetime
            e.Row.Cells[6].Width = 110;//client
            e.Row.Cells[7].Width = 110;//company
            e.Row.Cells[8].Width = 110;//account

            e.Row.Cells[9].Width = 35;//product type
            e.Row.Cells[10].Width = 150;//street #
            e.Row.Cells[11].Width = 180;//street add
            e.Row.Cells[12].Width = 180;//city
            e.Row.Cells[13].Width = 50;//state
            e.Row.Cells[14].Width = 80; //zip
            e.Row.Cells[15].Width = 80; //county
            e.Row.Cells[16].Width = 60; //procesor
            e.Row.Cells[17].Width = 60; //Driver
            e.Row.Cells[18].Width = 100; //int date
            e.Row.Cells[19].Width = 200; //appt comments
            e.Row.Cells[20].Width = 130; //status
            e.Row.Cells[21].Width = 200;//pi comments*/
            e.Row.Cells[20].Text = Utility.toCapital(e.Row.Cells[20].Text);
            e.Row.Cells[5].Text = Utility.Hora24horastoFormatoAMPM(e.Row.Cells[5].Text).strC1 + Utility.Hora24horastoFormatoAMPM(e.Row.Cells[5].Text).strC2;
            
            
            e.Row.Cells[11].Text = Utility.toCapital(e.Row.Cells[11].Text);
            e.Row.Cells[12].Text = Utility.toCapital(e.Row.Cells[12].Text);
            try
            {
                e.Row.Cells[20].Text = Utility.getsrtDate(e.Row.Cells[20].Text);
            } catch (Exception ex){
                Utility.writeError("No es valida la fecha para llenar APT DATE en WK "+ex.Message);
                e.Row.Cells[20].Text = "";
            }
            
             DataSet process = DB.getProcessProduct(1);
             string processname = null;

             
             if (process != null)
             {
                 
                 processname = process.Tables[0].Rows[0][0].ToString();
             }
       
            int intCampoVendor = DB.getCampoID(processname, "VENDOR");
            int intCampoDone = DB.getCampoID(processname, "DONE");
            e.Row.Cells[16].Text = intCampoVendor.ToString();
            e.Row.Cells[17].Text = intCampoDone.ToString();
            try
            {
                //escribiendo inicial de usuario
                string rxml;
                com.bpophotos.www.Service service = new com.bpophotos.www.Service();
                rxml = service.getDatosUsuario(e.Row.Cells[6].Text);
                rUser client = Utility.getRUser(rxml);
                e.Row.Cells[6].Text = client.getAlias();

                //escribiendo nombre compania

                string respuesta = "";
                
                respuesta = service.getCompany(e.Row.Cells[7].Text);
                if (!respuesta.Equals("") || respuesta != null)
                {
                    DataSet dsc = Utility.getCompanies(respuesta);

                    for (int ii = 0; ii <= (dsc.Tables[0].Rows.Count - 1); ii++)
                    {
                        if (dsc.Tables[0].Rows[ii][1].ToString() == "&nbsp;") { e.Row.Cells[7].Text = ""; }
                        else
                        {
                            e.Row.Cells[7].Text = dsc.Tables[0].Rows[ii][1].ToString();
                        }


                    }
                }
                //escribiendo inicial account
                string resp = null;
                resp = service.getAccount(e.Row.Cells[8].Text);
                if (resp!= "" || resp != null)
                {
                    DataSet dsclient = Utility.getAccounts(resp);
                   

                    for (int ii = 0; ii <= (dsclient.Tables[0].Rows.Count - 1); ii++)
                    {
                        e.Row.Cells[8].Text = dsclient.Tables[0].Rows[ii][2].ToString();
                       

                    }
                }

                // escribiendo procesador y driver
                int product_id = DB.getProductIdbyInitial(e.Row.Cells[9].Text);
                 DataSet dsprocess = DB.getProcessProduct(product_id);
                 int agent = 0; int processor = 0; int driver = 0;
                 if (dsprocess != null)
                 {
                     for (int j = 0; j <= (dsprocess.Tables[0].Rows.Count - 1); j++)
                     { //si el perfil del proceso es 3 (processor)
                         int orderid = int.Parse(e.Row.Cells[2].Text);
                         RE_GenericBean vendor = new RE_GenericBean();
                         vendor = DB.getValueCampo("VENDOR", orderid, dsprocess.Tables[0].Rows[j][0].ToString());
                         RE_GenericBean done = new RE_GenericBean();
                         done = DB.getValueCampo("DONE", orderid, dsprocess.Tables[0].Rows[j][0].ToString());
                         string nombre = "";
                         if (vendor != null)
                         {
                             nombre = vendor.strC1;
                         }
                         
                         string donestr = "";
                         if (done != null)
                         {
                             donestr = done.strC1;
                         }

                        if (dsprocess.Tables[0].Rows[j][1].ToString()=="3"){
                            processor = 1;
                            if (agent == 0)
                            {
                               
                                if (nombre!=""){
                                e.Row.Cells[16].Text = nombre;
                                if (donestr=="YES"){
                                    e.Row.Cells[16].Text = "<img src=\"..\\img\\greenstar.png \" align=\"left\" >";
                                }
                                }
                                else
                                {
                                    e.Row.Cells[16].Text = "";
                                }
                               
                                
                            }
                        }
                         // si es agente
                        if (dsprocess.Tables[0].Rows[j][1].ToString() == "5")
                        {
                            agent = 1;
                            processor = 1;
                            if (nombre != "")
                            {
                                e.Row.Cells[16].Text = nombre;
                                if (donestr == "YES")
                                {
                                    e.Row.Cells[16].Text = "<img src=\"..\\img\\greenstar.png \" align=\"left\" >";
                                   
                                }
                            }
                            else {
                                e.Row.Cells[16].Text = "";
                            }
                        }
                         // si es ddriver
                        if (dsprocess.Tables[0].Rows[j][1].ToString() == "2")
                        {
                            driver = 1;
                            if (nombre != "")
                            {
                                e.Row.Cells[17].Text = nombre;
                                
                                if (donestr == "YES")
                                {
                                    e.Row.Cells[17].Text = "<img src=\"..\\img\\greenstar.png \" align=\"left\" >";
                                }
                            }
                            else
                            {
                                e.Row.Cells[17].Text = "";
                            }
                        }
                     
                     }
                 }
                if (processor==0  ){
                    e.Row.Cells[16].Text = "VIC";
                    e.Row.Cells[16].Text = "<img src=\"..\\img\\greenstar.png \" align=\"left\" >";
                }
                if (driver == 0)
                {
                    e.Row.Cells[17].Text = "VIC";
                    e.Row.Cells[17].Text = "<img src=\"..\\img\\greenstar.png \" align=\"left\" >";
                }
            }
            catch (Exception ee)
            {

                Utility.writeError(ee.Message);
            }
        }
        
    }


    protected void gv_status_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
   
    protected void gv_status_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header ) {
            e.Row.Cells[0].Width = 50;
            e.Row.Cells[0].Text = "";
            e.Row.Cells[1].Style.Add("display","none");
            e.Row.Cells[3].Style.Add("display", "none");//hide color
            e.Row.Cells[2].Width = 100;
            e.Row.Cells[2].Text = "Summary Orders";
            e.Row.Cells[4].Text = "";
            e.Row.Cells[4].Width = 50;
            
        

        }
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Cells[1].Style.Add("display", "none");
            e.Row.Cells[3].Style.Add("display", "none");
         
             e.Row.Cells[0].Width = 50;//color
             e.Row.Cells[2].Width = 100;//status
             e.Row.Cells[4].Width = 50;//count
             e.Row.Cells[0].Text = "<img src=\""+e.Row.Cells[0].Text+" \" align=\"middle\" >";
             if ((long.Parse(ruser.getPermiso()) & 8) == 8)
             {
                 
                 if (e.Row.Cells[2].Text.ToUpper().Equals("PAID")){
                 e.Row.Cells[2].Text = "<A href=\"WorkSpace.aspx?get=paid\">"  + e.Row.Cells[2].Text + " </A>";
                 }
             }
            
        }
    }


   

    int GetSortColumnIndex()
    {

        foreach (DataControlField field in gv_detail.Columns)
        { 
            if (field.SortExpression == gv_detail.SortExpression)
            {
                return gv_detail.Columns.IndexOf(field);
            }
        }

        return -1;
    }
    protected void sorting(object sender, GridViewSortEventArgs e)
    {
        if (Session["OrderList"] != null)
            ds = (DataSet)Session["OrderList"];

        if (ds != null)
        {
            if (!e.SortExpression.Equals("County") || (!e.SortExpression.Equals("Order #")) || (!e.SortExpression.Equals("Due Date")) || (!e.SortExpression.Equals("Due Time")) || (!e.SortExpression.Equals("Type")) || (!e.SortExpression.Equals("Street No.")) || (!e.SortExpression.Equals("Street Address")) || (!e.SortExpression.Equals("City")) || (!e.SortExpression.Equals("State")) || (!e.SortExpression.Equals("Zip")))
          {
            DataView dv = (DataView)(ds.Tables["Tabla"].DefaultView);
            if ((sort % 2) == 0)
                dv.Sort = e.SortExpression + " " + "ASC";
            else
                dv.Sort = e.SortExpression + " " + "DESC";
           // dv.Sort = e.SortExpression+" "+ ConvertSortDirection(e.SortDirection) ;
            sort++;
            gv_detail.DataSource = dv;
            
            gv_detail.DataBind();
          }
        }
    }

    private string ConvertSortDirection(SortDirection sortDirection)
    {
        string newSortDirection = String.Empty;
        switch (sortDirection)
        {
            case SortDirection.Ascending:
                newSortDirection = "ASC";
                
                break;

            case SortDirection.Descending:
                newSortDirection = "DESC";
                break;
        }

        return newSortDirection;
    }
    protected void sorted(object sender, EventArgs e)
    {
       
    }
}
